<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Token;
use app\common\library\Upload;
use app\common\model\Binding;
use app\common\model\Canal;
use app\common\model\Collision;
use app\common\model\Follow;
use app\common\model\Ibec;
use app\common\model\Report;
use app\common\model\Scan;
use app\common\model\Show;
use app\common\model\Staff;
use app\common\model\Type;
use Exception;
use think\Db;
use think\Response;

/**
 * 客户管理接口
 */
class Connection extends Api
{
    protected $noNeedLogin = ['tasks', 'reportExpire','collision'];
    protected $noNeedRight = ['*'];


    /**
     *处理撞单数据
     * */
    public function collision(){
        /*$model=new \app\common\model\Connection();
        $connection = $model->whereNotIn("status",['2','4'])->where("canal_id >0")->select();
        $updata=[];
        foreach ($connection as $k=>$v){
            $where = "phone = " . $v["phone"] . " or (phone_two is not null and phone_two=" . $v["phone"] . ") ";
            if (!empty($v["phone_two"])) {
                $where .= " or phone=" . $v["phone_two"] . " or (phone_two is not null and phone_two=" . $v["phone_two"] . ") ";
            }
            $bind = \app\common\model\Connection::where(["type_data" => '0', "status" => '2'])->where($where)
                ->find();
            if (!empty($bind) && empty($v["canal_id"])) {
                $updata[$k]["canal_id"] = $bind["canal_id"];
                $updata[$k]["id"] = $v["id"];
            }
        }
        if(!empty($updata)){
            $model->saveAll($updata);
        }*/
        /*修改置业顾问end*/
        $list=Collision::all();
        $data=[];
        foreach ($list as $k=>$v){
            $bind_staff=Staff::field("ibec_id")->where(["id"=>$v["bind_staff_id"]])->find();
            $staff=Staff::field("ibec_id")->where(["id"=>$v["staff_id"]])->find();
            if(!empty($bind_staff)){
                $bind_staff_ibec=Ibec::field("id,name")->where(["id"=>$bind_staff["ibec_id"]])->find();
            }
            if(!empty($staff)){
                $staff_ibec=Ibec::field("id,name")->where(["id"=>$staff["ibec_id"]])->find();
            }
            $data[$k]=[
                "id"=>$v["id"],
                "bind_staff_ibec_id"=>$bind_staff_ibec["id"]??0,
                "bind_staff_ibec_name"=>$bind_staff_ibec["name"]??'',
                "staff_ibec_id"=>$staff_ibec["id"]??0,
                "staff_ibec_name"=>$staff_ibec["name"]??'',
            ];
        }
        if(!empty($data)){
            $model=new Collision();
            $model->saveAll($data);
        }

    }


    /**
     * 录入客户
     * */
    public function add()
    {
        $user = $this->auth->getUser();
        //$user=Staff::get(21);
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 1) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        $data = [
            ['surname', 'require', '客户姓不能为空'],
            ['phone', 'require', '客户手机号码不能为空'],
            ['estimate_time', 'require', '预计到访时间不能为空'],
            ['type', 'require', '客户类型不能为空'],
            ['type_id', 'require', '客户类型不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $model = new \app\common\model\Connection();
        $param = $this->request->param();
        if (strlen($param["phone"]) != 7) $this->error("请检查手机号码");
        $user_list = $model->field("id")->where(["surname" => $param['surname'], "phone" => $param['phone'], "staff_id" => $user["id"]])->find();
        if (!empty($user_list)) $this->error("您已经录入过该客户资料");
        /*$list=$model->field("id")->where(["surname"=>$param['surname'],"phone"=>$param['phone']])->find();
        if(!empty($list)){
            //撞单
            $param["connection_id"]=$list["id"];
            $param["collision_data"]=1;
        }*/
        $param["staff_id"] = $user["id"];
        $param["ibec_id"] = $user["ibec_id"];
        $param["moniker"] = $param["surname"] . $param["name"];
        $param["estimate_time"] = strtotime($param["estimate_time"]);
        $param["phone_see"] = substr($param["phone"], 0, 3) . "****" . substr($param["phone"], -4, 4);
        /*新增 start*/
        if (!isset($result['phone_two'])) {
            if (strlen($param["phone_two"]) != 7 && !empty($param["phone_two"])) $this->error("请检查手机号码");
            if (!empty($param['phone_two'])) $param["phone_two_see"] = substr($param["phone_two"], 0, 3) . "****" . substr($param["phone_two"], -4, 4);
        }
        /*新增 end*/
        if ($user["type_data"] == 1) {
            //经纪人公司驻场
            if ($this->request->param("staff_id") && !empty($this->request->param("staff_id"))) {
                //如果指派了经纪人
                $staff = Staff::get($this->request->param("staff_id"));
                if (!empty($staff)) {
                    $param["staff_id"] = $this->request->param("staff_id");
                }
            }
            $param["entryibec_id"] = $user["id"];
        }
        $param["createtime"] = time();
        Db::startTrans();
        try {
            $id = $model->allowField(true)->insertGetId($param);
            /*生成二维码 start*/
            $config = get_addon_config('qrcode');
            $qrCode = \addons\qrcode\library\Service::qrcode(["text" => "connection_id=" . $id]);
            // 写入到文件
            $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            if (is_really_writable($qrcodePath)) {
                $filePath = $qrcodePath . md5("connection_id" . $id) . '.' . $config['format'];
                $qrCode->writeFile($filePath);
            }
            $url = cdnurl("/uploads/qrcode/" . md5("connection_id" . $id) . '.' . $config['format']);
            /*生成二维码 end*/
            $model->where(["id" => $id])->update(["code" => $url]);
            /*查找同一客户是否有绑定经纪人*/
            $connection = \app\common\model\Connection::where(["surname" => $param["surname"], "phone" => $param["phone"], "status" => '2'])->find();
            if (!empty($connection)) {
                \app\common\model\Connection::where(["id" => $id])->update(["bind_staff_id" => $connection["bind_staff_id"], "bind_time" => $connection["bind_time"]]);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("成功");
    }

    /**
     * 报备
     * */
    public function addReport()
    {
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 1) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        if (!$this->request->param("connection_id")) $this->error("客户id为空");
        $connection = \app\common\model\Connection::find($this->request->param("connection_id"));
        if (empty($connection)) $this->error("客户不存在");
        $appointCanal = \think\Config::get('site.appointCanal');
        $updata = ["status" => '1', "report_time" => time()];
        if ($appointCanal == 1) {
            if (!$this->request->param("canal_id")) $this->error("置业顾问id为空");
            $canal = Canal::find($this->request->param("canal_id"));
            if (empty($canal)) $this->error("置业顾问不存在");
            $updata["canal_id"] = $this->request->param("canal_id");
        }
        if ((int)$connection["status"] == 1) $this->error("客户已报备");
        if ((int)$connection["status"] == 4) $this->error("客户已成交");
        Db::startTrans();
        try {
            Report::create([
                "connection_id" => $this->request->param("connection_id"),
                "staff_id" => $this->auth->id,
            ]);
            $where = "phone = " . $connection["phone"] . " or (phone_two is not null and phone_two=" . $connection["phone"] . ") ";
            if (!empty($connection["phone_two"])) {
                $where .= " or phone=" . $connection["phone_two"] . " or (phone_two is not null and phone_two=" . $connection["phone_two"] . ") ";
            }
            $bind = \app\common\model\Connection::where(["type_data" => '0', "status" => '2'])->where($where)
                ->find();
            if (!empty($bind)) {
                $updata["bind_staff_id"] = $bind["bind_staff_id"];
                //2023-6-27 注释置业顾问绑定
                //$updata["canal_id"] = $bind["canal_id"];
                $updata["lapse_time"] = $bind["lapse_time"];
                $updata["bind_time"] = time();
            }
            $connection->save($updata);
            /*新增撞单记录 start*/
            //$list = \app\common\model\Connection::where(["surname" => $connection["surname"], "phone" => $connection["phone"], "status" => '2', "type_data" => '0'])->select();
            $list = \app\common\model\Connection::where(["status" => '2', "type_data" => '0'])
                ->where($where)->select();
            $collision_data = [];
            if (!empty($list)) {
                $staff_user = Staff::field("name,mobile,ibec_id")->find(["id" => $connection["staff_id"]]);
                foreach ($list as $k => $v) {
                    $staff = Staff::find($v["bind_staff_id"]);
                    $collision_data[$k]["connection_id"] = $v["id"];
                    $collision_data[$k]["connection_name"] = $v["moniker"];
                    $collision_data[$k]["connection_mobile"] = $v["phone"];
                    $collision_data[$k]["connection_mobile_see"] = $v["phone_see"];
                    /*新增 start*/
                    $canal = Canal::field("id,name")->where(["id" => $v["canal_id"]])->find();
                    $collision_data[$k]["canal_id"] = !empty($canal) ? $canal["id"] : 0;
                    $collision_data[$k]["canal_name"] = !empty($canal) ? $canal["name"] : '';//置业顾问
                    $collision_data[$k]["connection_mobile_two"] = !empty($v["phone_two"]) ? $v["phone_two"] : '';
                    $collision_data[$k]["connection_mobile_two_see"] = !empty($v["phone_two_see"]) ? $v["phone_two_see"] : '';
                    /*新增 end*/
                    $collision_data[$k]["bind_staff_id"] = $v["bind_staff_id"];
                    $collision_data[$k]["bind_staff_name"] = !empty($staff) ? $staff["name"] : '';
                    $collision_data[$k]["bind_staff_mobile"] = !empty($staff) ? $staff["mobile"] : '';
                    $ibec = Ibec::field("name")->find(["id" => $staff["ibec_id"]]);
                    $collision_data[$k]["bind_staff_ibec_name"] = !empty($ibec) ? $ibec["name"] : '';
                    $collision_data[$k]["staff_id"] = $connection["staff_id"];
                    $collision_data[$k]["staff_name"] = !empty($staff_user) ? $staff_user["name"] : '';
                    $collision_data[$k]["staff_mobile"] = !empty($staff_user) ? $staff_user["mobile"] : '';
                    $collision_data[$k]["staff_connection_id"] = $connection["id"];
                    $ibec = Ibec::field("name")->find(["id" => $staff_user["ibec_id"]]);
                    $collision_data[$k]["staff_ibec_name"] = !empty($ibec) ? $ibec["name"] : '';
                    $collision_data[$k]["createtime"] = time();
                }
                if (!empty($collision_data)) {
                    Collision::insertAll($collision_data);
                }
            }
            /*新增撞单记录 end*/
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("成功");

    }

    /**
     * 经纪人客户列表
     * */
    public function canaStafflList()
    {
        $user = $this->auth->getUser();
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 1) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $where = "1=1";
        $where2 = "1=1";
        $staff_where = ["staff_id" => $this->auth->id];
        if ($this->request->param('search') != '') {
            $search = $this->request->param('search');
            //客户编号、客户姓名，绑定经纪人姓名，经纪人电话
            /*1.普通经纪人检索框只是通过姓名/手机号进行检索
            2.经纪人驻场可通过姓名/手机号/分配经纪人姓名进行检索*/
            $where = " moniker like '%" . $search . "%'  or staff.name like '%" . $search . "%'";
            if (is_numeric($search)) {
                $where .= "or phone like '%" . $search . "%'";// or connection.id =".$search;
            }
            if ($user["type_data"] == 1) {
                //经纪人驻场
                $where .= " or staff.name like '%" . $search . "%'";
                if (is_numeric($search)) {
                    $where .= " or staff.mobile like '%" . $search . "%'";
                }
            }
        }
        if ($this->request->param('status') != '') {
            $status = $this->request->param('status');
            //status 状态:0=已录入,1=已报备,2=已绑定,3=已失效,4=已成交
            $where2 = ["connection.status" => $status];
        }
        if ($user["type_data"] == 1) {
            //经纪人驻场
            $staff_where = "staff_id in(select id from dc_staff where ibec_id=" . $user["ibec_id"] . ")";
        }
        $list = \app\common\model\Connection::field("id,connection.status,moniker,phone_see,code,
        IF(FLOOR((lapse_time-UNIX_TIMESTAMP())/3600/24)>0,FLOOR((lapse_time-UNIX_TIMESTAMP())/3600/24)+1,0) lapse_time,
        from_unixtime(estimate_time, '%Y-%m-%d %H:%i') estimate_time,phone_two_see,report_time")
            ->with(["staff" => function ($query) {
                $query->withField('id,name,mobile');
            }, "canal" => function ($query) {
                $query->withField('id,name,mobile');
            }])
            ->where($staff_where)
            ->where($where)
            ->where($where2)
            ->order("connection.createtime", "desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功", $list);
    }

    /**
     * 处理绑定过期客户
     * */
    public function bindExpire()
    {
        if (!$this->request->param("connection_id")) $this->error("客户id为空");
        $connection = \app\common\model\Connection::find($this->request->param("connection_id"));
        if (empty($connection)) $this->error("客户不存在");
        if ((int)$connection["status"] != 2) $this->error("客户状态错误");
        $connection->status = '3';
        $connection->save();
        $this->success("成功");
    }

    /*************************** 渠道驻场*****************************************************************/
    /**
     * 渠道驻场扫码绑定客户与经纪人
     * */
    public function bind()
    {
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 3) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        if (!$this->request->param("connection_id")) $this->error("客户id为空");
        if (!$this->request->param("canal_id")) $this->error("请选择置业顾问");
        $canal = Canal::find($this->request->param("canal_id"));
        $loseTime = \think\Config::get('site.loseTime');
        if ($this->request->param("connection_id")) {
            //经纪人录入客户
            $connection = \app\common\model\Connection::find($this->request->param("connection_id"));
            if (empty($connection)) $this->error("客户不存在");
            /*if((int)$connection["status"]>=2){

                $this->error("客户已绑定");
            }*/
            if ($connection["type_data"] == 1) {
                //自然流量客户
                $data = [
                    "connection_id" => $connection["id"],
                    "connection_name" => $connection["moniker"],
                    "connection_mobile" => $connection["phone"],
                    "connection_mobile_see" => $connection["phone_see"],
                    "staff_id" => 0,
                    "staff_name" => '',
                    "staff_mobile" => '',
                    "canal_id" => $this->request->param("canal_id"),
                    "canal_name" => !empty($canal) ? $canal["name"] : '',
                    "canal_mobile" => !empty($canal) ? $canal["mobile"] : '',
                    "createtime" => time(),
                    "dynatown_id" => $this->auth->id,
                    "type_data" => '1',
                ];
                $connection->save(["canal_id" => $this->request->param("canal_id")]);
            } else {
                if ($connection["status"] != '1' && $connection["status"] != '2') $this->error("请先报备再扫码");
                $staff = Staff::find($connection["staff_id"]);
                //$bind=Binding::where(["connection_id"=>$connection["id"]])->where("lapse_time > ".time())->find();
                $entry_staff_ibec = \app\common\model\Ibec::field("id,name")->where(["id" => $staff["ibec_id"]])->find();//录入经纪人公司
                //$canal=Canal::field("id,name,mobile")->where(["id"=>$connection["canal_id"]])->find();//置业顾问
                $data = [
                    "connection_id" => $connection["id"],
                    "connection_name" => $connection["moniker"],
                    "connection_mobile" => $connection["phone"],
                    "connection_mobile_see" => $connection["phone_see"],
                    /*新增 start*/
                    "connection_mobile_two" => !empty($connection["phone_two"])?$connection["phone_two"]:0,
                    "connection_mobile_two_see" =>!empty($connection["phone_two_see"])? $connection["phone_two_see"]:0,
                    /*新增 end*/
                    "staff_id" => $connection["staff_id"],
                    "staff_name" => $staff["name"],
                    "staff_mobile" => $staff["mobile"],
                    "entry_staff_id" => $connection["staff_id"],
                    "entry_staff_name" => $staff["name"],
                    "entry_staff_mobile" => $staff["mobile"],
                    /*新增 start*/
                    "entry_staff_ibec_id" => !empty($entry_staff_ibec) ? $entry_staff_ibec["id"] : 0,
                    "entry_staff_ibec_name" => !empty($entry_staff_ibec) ? $entry_staff_ibec["name"] : '',
                    "staff_ibec_id" => !empty($entry_staff_ibec) ? $entry_staff_ibec["id"] : 0,
                    "staff_ibec_name" => !empty($entry_staff_ibec) ? $entry_staff_ibec["name"] : '',
                    /*新增 end*/
                    "canal_id" => $this->request->param("canal_id"),
                    "canal_name" => empty($canal) ? '' : $canal["name"],
                    "canal_mobile" => empty($canal) ? '' : $canal["mobile"],
                    "createtime" => time(),
                    "dynatown_id" => $this->auth->id,
                ];
                /*新增过期时间 start*/
                $lapse_time = strtotime("+" . $loseTime . " days", strtotime(date("Y-m-d", time())));
                $data["lapse_time"] = $lapse_time;
                /*新增过期时间 end*/
                if (!empty($connection["bind_staff_id"]) && $connection["lapse_time"] >= time()) {
                    Db::startTrans();
                    try {
                        //如果当前客户绑定了经纪人并且没失效
                        $staff = Staff::find($connection["bind_staff_id"]);
                        $canal = Canal::find($connection["canal_id"]);
                        if (!empty($staff)) {
                            $data["staff_id"] = $staff["id"];
                            $data["staff_name"] = $staff["name"];
                            $data["staff_mobile"] = $staff["mobile"];
                        }
                        if (!empty($canal)) {
                            $data["canal_id"] = $canal["id"];
                            $data["canal_name"] = $canal["name"];
                            $data["canal_mobile"] = $canal["mobile"];
                        }
                        /*新增 start*/
                        $staff_ibec = \app\common\model\Ibec::field("id,name")->where(["id" => $staff["ibec_id"]])->find();//绑定经纪人公司
                        $data["staff_ibec_id"] = !empty($staff_ibec) ? $staff_ibec["id"] : 0;
                        $data["staff_ibec_name"] = !empty($staff_ibec) ? $staff_ibec["name"] : '';
                        /*新增 end*/
                        /*新增撞单记录 start*/
                        /*修改 匹配两个手机号有一个相同 start*/
                        /*$list = \app\common\model\Connection::where(["surname" => $connection["surname"], "phone" => $connection["phone"], "type_data" => '0'])
                            ->where("status !='4'")
                            ->select();*/
                        $where = "phone = " . $connection["phone"] . " or (phone_two is not null and phone_two=" . $connection["phone"] . ") ";
                        if (!empty($connection["phone_two"])) {
                            $where .= " or phone=" . $connection["phone_two"] . " or (phone_two is not null and phone_two=" . $connection["phone_two"] . ") ";
                        }
                        $list = \app\common\model\Connection::where(["type_data" => '0', "status" => '2'])
                            ->where($where)->select();
                        /*修改 匹配两个手机号有一个相同 end*/
                        /*$bind = \app\common\model\Connection::where([
                            "surname" => $connection["surname"], "phone" => $connection["phone"], "type_data" => '0',"status"=>'2'])
                            ->find();//查找已绑定客户*/
                        $collision_data = [];
                        $update = [];
                        $time = time();
                        if (!empty($list)) {
                            $staff_user = Staff::field("name,mobile,ibec_id")->find(["id" => $connection["staff_id"]]);
                            foreach ($list as $k => $v) {
                                $collision = Collision::where(["connection_id" => $v["id"],"staff_connection_id"=>$connection["id"]])
                                    ->find();//撞单信息查询
                                if(empty($collision)&& $v["id"] != $connection["id"]){
                                    $staff = Staff::find($v["bind_staff_id"]);
                                    $collision_data[$k]["connection_id"] = $v["id"];
                                    $collision_data[$k]["connection_name"] = $v["moniker"];
                                    $collision_data[$k]["connection_mobile"] = $v["phone"];
                                    $collision_data[$k]["connection_mobile_see"] = $v["phone_see"];
                                    /*新增 start*/
                                    $canal = Canal::field("id,name")->where(["id" => $v["canal_id"]])->find();
                                    $collision_data[$k]["canal_id"] = !empty($canal) ? $canal["id"] : 0;
                                    $collision_data[$k]["canal_name"] = !empty($canal) ? $canal["name"] : '';//置业顾问
                                    $collision_data[$k]["connection_mobile_two"] = !empty($v["phone_two"]) ? $v["phone_two"] : '';
                                    $collision_data[$k]["connection_mobile_two_see"] = !empty($v["phone_two_see"]) ? $v["phone_two_see"] : '';
                                    /*新增 end*/
                                    $collision_data[$k]["bind_staff_id"] = $v["bind_staff_id"];
                                    $collision_data[$k]["bind_staff_name"] = !empty($staff) ? $staff["name"] : '';
                                    $collision_data[$k]["bind_staff_mobile"] = !empty($staff) ? $staff["mobile"] : '';
                                    $ibec = Ibec::field("name")->find(["id" => $staff["ibec_id"]]);
                                    $collision_data[$k]["bind_staff_ibec_name"] = !empty($ibec) ? $ibec["name"] : '';
                                    $collision_data[$k]["staff_id"] = $connection["staff_id"];
                                    $collision_data[$k]["staff_name"] = !empty($staff_user) ? $staff_user["name"] : '';
                                    $collision_data[$k]["staff_mobile"] = !empty($staff_user) ? $staff_user["mobile"] : '';
                                    $collision_data[$k]["staff_connection_id"] = $connection["id"];
                                    $ibec = Ibec::field("name")->find(["id" => $staff_user["ibec_id"]]);
                                    $collision_data[$k]["staff_ibec_name"] = !empty($ibec) ? $ibec["name"] : '';
                                    $collision_data[$k]["createtime"] = time();
                                }
                            }
                            if (!empty($collision_data)) {
                                Collision::insertAll($collision_data);
                            }
                            if (!empty($update)) {
                                $model = new \app\common\model\Connection();
                                $model->saveAll($update);
                            }
                            if (empty($collision)) {
                                $model = new \app\common\model\Connection();
                                $model->save([
                                    "bind_time" => $time,
                                    "bind_staff_id" => $connection["bind_staff_id"],
                                ], ["id" => $connection["id"]]);
                            }
                        }
                        /*新增撞单记录 end*/
                        Scan::create($data);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    $this->error("该客户已绑定");
                }
            }

            Db::startTrans();
            try {
                /*新增绑定记录 start*/
                $time = time();
                $lapse_time = strtotime("+" . $loseTime . " days", strtotime(date("Y-m-d", time())));
                /*判断两个手机号有一个相同 start*/
                /*$list = \app\common\model\Connection::where(["surname" => $connection["surname"], "phone" => $connection["phone"], "type_data" => '0'])
                    ->where("status !='4'")->select();*/

                /*$where="phone = ".$connection["phone"]." or (phone_two is not null and phone_two=".$connection["phone"].") ";
                if(!empty($connection["phone_two"])){
                    $where.=" or phone=".$connection["phone_two"]." or (phone_two is not null and phone_two=".$connection["phone_two"].") ";
                }
                $list = \app\common\model\Connection::where([ "type_data" => '0'])->where("status !='4'")
                    ->where($where)->select();
                if(!empty($list)){

                    foreach ($list as $k => $v) {
                        $update[$k] = [
                            "bind_time" => $time,
                            "id" => $v["id"],
                            "bind_staff_id" => $connection["staff_id"],
                            "lapse_time" => $lapse_time,
                        ];
                    }
                    if (!empty($update)) {
                        $model = new \app\common\model\Connection();
                        $model->saveAll($update);
                    }
                }
                }*/
                Binding::create([
                    "connection_id" => $connection["id"],
                    "staff_id" => $connection["staff_id"],
                    "lapse_time" => $lapse_time,
                    "createtime" => time(),
                    "dynatown_id" => $this->auth->id,
                ]);
                Scan::create($data);
                if ($connection["type_data"] == 0) {
                    //录入客户
                    /*新增撞单记录 start*/

                    /*判断两个手机号有一个相同 start*/
                    /* $list = \app\common\model\Connection::where(["surname" => $connection["surname"], "phone" => $connection["phone"], "type_data" => '0'])
                         ->where("status !='4'")
                         ->select();*/
                    $where = "phone = " . $connection["phone"] . " or (phone_two is not null and phone_two=" . $connection["phone"] . ") ";
                    if (!empty($connection["phone_two"])) {
                        $where .= " or phone=" . $connection["phone_two"] . " or (phone_two is not null and phone_two=" . $connection["phone_two"] . ") ";
                    }
                    $list = \app\common\model\Connection::where(["type_data" => '0'])->where("status !='4'")
                        ->where($where)->select();

                    $bind = \app\common\model\Connection::where(["type_data" => '0',"status"=>'2'])
                        ->where($where)->select();//查找已绑定客户
                    if(empty($bind)){
                        $connection->save(["status" => '2', "canal_id" => $this->request->param("canal_id"), "lapse_time" => $lapse_time]);//修改客户状态
                    }
                    /*判断两个手机号有一个相同 end*/
                    /* $bind = \app\common\model\Connection::where([
                         "surname" => $connection["surname"], "phone" => $connection["phone"], "type_data" => '0',"status"=>'2'])
                         ->find();//查找已绑定客户*/
                    $collision_data = [];
                    if (!empty($list)) {
                        if (!empty($list)) {
                            foreach ($list as $k => $v) {
                                $collision = Collision::where(["connection_id" => $v["id"],"staff_connection_id"=>$connection["id"]])
                                    ->find();//撞单信息查询
                                if ($v["status"] == 1 && $v["id"] != $connection["id"] && empty($collision)) {
                                    $collision_data[$k]["connection_id"] = $connection["id"];
                                    $collision_data[$k]["connection_name"] = $connection["moniker"];
                                    $collision_data[$k]["connection_mobile"] = $connection["phone"];
                                    $collision_data[$k]["connection_mobile_see"] = $connection["phone_see"];
                                    /*新增 start*/
                                    $collision_data[$k]["connection_mobile_two"] = $connection["phone_two"];
                                    $collision_data[$k]["connection_mobile_two_see"] = $connection["phone_two_see"];
                                    $collision_data[$k]["canal_id"] = !empty($canal) ? $canal["id"] : 0;
                                    $collision_data[$k]["canal_name"] = !empty($canal) ? $canal["name"] : '';
                                    /*新增 end*/
                                    $collision_data[$k]["bind_staff_id"] = $connection["bind_staff_id"];
                                    $collision_data[$k]["bind_staff_name"] = $staff["name"];
                                    $collision_data[$k]["bind_staff_mobile"] = $staff["mobile"];
                                    $collision_data[$k]["staff_id"] = $v["staff_id"];
                                    $staff_user = Staff::field("name,mobile")->find(["id" => $v["staff_id"]]);
                                    if (!empty($staff_user)) {
                                        $collision_data[$k]["staff_name"] = $staff_user["name"];
                                        $collision_data[$k]["staff_mobile"] = $staff_user["mobile"];
                                    }
                                    $collision_data[$k]["staff_connection_id"] = $v["id"];
                                    $collision_data[$k]["createtime"] = time();
                                }
                                $update[$k] = [
                                    "bind_time" => $time,
                                    "id" => $v["id"],
                                    "bind_staff_id" => $connection["staff_id"],
                                    "lapse_time" => $lapse_time,
                                    //2023-6-27 注释置业顾问绑定
                                    //"canal_id" => $connection["canal_id"],
                                ];
                            }
                            if (!empty($collision_data)) {
                                Collision::insertAll($collision_data);
                            }
                            if (!empty($update)) {
                                $model = new \app\common\model\Connection();
                                $model->saveAll($update);
                            }
                        }
                    }
                    /*新增撞单记录 end*/
                }

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->success("成功");
    }

    /**
     * 扫码记录
     * */
    public function scanList()
    {
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 3) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $where = "1=1";
        if ($this->request->param('search')) {
            $search = $this->request->param('search');
            //客户编号、客户姓名，客户电话（前三位+后四位），绑定经纪人姓名，置业顾问
            $where = "  connection_name like '%" . $search . "%' or staff_name like '%" . $search . "%' or canal_name like '%" . $search . "%'";
            if (is_numeric($search)) {
                $where .= " or connection_id =" . $search . " or connection_mobile like '%" . $search . "%'";
            }
        }
        $list = Scan::field("id,connection_id,connection_name,connection_mobile_see,staff_name,staff_mobile,canal_name,
        canal_mobile,FROM_UNIXTIME(createtime, '%Y-%m-%d %H:%i') createtime,connection_mobile_two_see,entry_staff_ibec_name,staff_ibec_name")
            ->where(["dynatown_id" => $this->auth->id])
            ->where($where)
            ->order("createtime", "desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v) {
                $v["canal_mobile"] = substr_replace($v["canal_mobile"], '****', 3, 4);
            });
        $this->success("成功", $list);
    }

    /*************************** 置业顾问*****************************************************************/
    /**
     * 置业顾问填写带看记录
     * */
    public function addShow()
    {
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 2) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        $user = $this->auth->getUser();
        $data = [
            ['connection_id', 'require', '客户不能为空'],
            ['intention', 'require', '意向等级不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        $list = \app\common\model\Connection::get($param["connection_id"]);
        if (empty($list)) $this->error("客户不存在");
        $scan=Scan::field("createtime")->where(["connection_id"=>$param["connection_id"]])->order("createtime","desc")->find();
        if(empty($scan)) $this->error("请先到渠道部驻场扫码！");
        $model = new Show();
        $show=$model->where(["connection_id"=>$param["connection_id"]])->where("createtime > ".$scan["createtime"])->find();
        if(!empty($show)) $this->error("请先到渠道部驻场扫码！");
        $staff = Staff::get($list["bind_staff_id"]);
        $entry = Staff::get($list["staff_id"]);//录入经纪人
        if (empty($list["type_data"])) {
            //绑定经纪人
            $param["staff_id"] = $list["bind_staff_id"];
            $param["staff_name"] = empty($staff) ? '' : $staff["name"];
            $param["staff_mobile"] = empty($staff) ? '' : $staff["mobile"];
            //录入经纪人
            $param["entry_staff_id"] = $entry["id"];
            $param["entry_staff_name"] = empty($entry) ? '' : $entry["name"];
            $param["entry_staff_mobile"] = empty($entry) ? '' : $entry["mobile"];
        }
        $param["connection_name"] = $list["moniker"];
        $param["connection_mobile"] = $list["phone"];
        $param["connection_mobile_see"] = $list["phone_see"];
        /*新增 start*/
        $param["connection_mobile_two"] = $list["phone_two"];
        $param["connection_mobile_two_see"] = $list["phone_two_see"];
        /*新增 end*/
        $param["canal_id"] = $user["id"];
        $param["canal_name"] = $user["name"];
        $param["canal_mobile"] = $user["mobile"];
        $param["type_data"] = $list["type_data"];//类型:0=录入客户,1=自然流量
        $model->allowField(true)->save($param);
        $this->success("成功");
    }

    /**
     * 置业顾问填写跟进记录
     * */
    public function addFollow()
    {
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 2) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        $user = $this->auth->getUser();
        $data = [
            ['connection_id', 'require', '客户不能为空'],
            ['show_id', 'require', '带看不能为空'],
            ['content', 'require', '跟进记录不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        $model = new Follow();
        /*$scan=Scan::field("createtime")->where(["connection_id"=>$param["connection_id"]])->order("createtime","desc")->find();
        if(empty($scan)) $this->error("请先到渠道部驻场扫码！");
        $follow=$model->where(["connection_id"=>$param["connection_id"]])->where("createtime > ".$scan["createtime"])->find();
        if(!empty($follow)) $this->error("请先到渠道部驻场扫码！");*/
        $param["canal_id"] = $user["id"];
        $model->allowField(true)->save($param);
        $this->success("成功");
    }

    /**
     * 跟进记录
     * */
    public function followList()
    {
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 2) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        if (!$this->request->param("show_id")) $this->error("id为空");
        $model = new Follow();
        $list = $model->field("id,content,from_unixtime(createtime, '%Y') year,from_unixtime(createtime, '%m.%d') date")
            ->where(["show_id" => $this->request->param("show_id")])->order("createtime", "desc")->select();
        $this->success("成功", $list);
    }

    /**
     * 带看记录
     * */
    public function showList()
    {
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 2) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $where = "1=1";
        $connection_where = "1=1";
        if ($this->request->param('search')) {
            $search = $this->request->param('search');
            //客户编号、客户姓名，绑定经纪人姓名，意向类型
            $where = " connection_name like '%" . $search . "%' or staff_name like '%" . $search . "%' or intention like '%" . $search . "%'";
            if (is_numeric($search) && !$this->request->param('connection_id')) {
                $where .= " or connection_id =" . $search;
            }
        }
        if ($this->request->param('connection_id') && !empty($this->request->param('connection_id'))) {
            $connection_where = ["connection_id" => $this->request->param('connection_id')];
        }
        $canal_where=["canal_id" => $this->auth->id];
        $user=$this->auth->getUser();
        if($user["type_data"]==1){
            //组长
            $canal_where="canal_id = ".$this->auth->id." or canal_id in (select id from dc_canal where pid = ".$this->auth->id.")";
        }
        $list = Show::field("id,connection_id,connection_name,intention,connection_mobile_see,staff_name,staff_mobile,canal_name,canal_mobile,from_unixtime(createtime, '%Y-%m-%d %H:%i') createtime,connection_mobile_two_see")
            ->where($canal_where)
            ->where($where)
            ->where($connection_where)
            ->order("createtime", "desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v) {
                $v["canal_mobile"] = substr_replace($v["canal_mobile"], '****', 3, 4);
            });
        $this->success("成功", $list);
    }

    /**
     * 置业顾问客户列表
     * */
    public function canalConnectionList()
    {
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 2) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $where = "1=1";
        $where2 = "1=1";
        if ($this->request->param('search')) {
            $search = $this->request->param('search');
            //客户编号、客户姓名，绑定经纪人姓名，经纪人电话
            $where = " moniker like '%" . $search . "%'  or bindStaff.name like '%" . $search . "%'";
            if (is_numeric($search)) {
                $where .= "or bindStaff.mobile like '%" . $search . "%' or connection.id =" . $search;
            }
        }
        if ($this->request->param('status')) {
            $status = $this->request->param('status');
            //status 1已成交,2进行中
            $where2 = " connection.status ='4'";// and strike_data='1'
            if ($status == 2) {
                $where2 = " connection.status <>'4'";
            }
        }
        $canal_where=["canal_id" => $this->auth->id];
        $user=$this->auth->getUser();
        if($user["type_data"]==1){
            //组长
            $canal_where="canal_id = ".$this->auth->id." or canal_id in (select id from dc_canal where pid = ".$this->auth->id.")";
        }
        $list = \app\common\model\Connection::field("id,status,moniker,phone_see,estimate_time,type_data,phone_two_see")
            ->with(["bindStaff" => function ($query) {
                $query->withField('id,name,mobile,ibec_id');
            },"canal" => function ($query) {
                $query->withField('id,name,mobile');
            }])
            ->field("connection.*,ibec.name ibec_name")
            ->join("ibec","ibec.id=bindStaff.ibec_id","left")
            ->where($where)
            ->where($canal_where)
            ->where($where2)
            ->order("connection.createtime", "desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功", $list);
    }

    /**
     * 客户详情
     * */
    public function connectionSee()
    {
        if (!$this->request->param("connection_id")) $this->error("id为空");
        $list = \app\common\model\Connection::field("id,moniker,phone_see,from_unixtime(estimate_time, '%Y-%m-%d %H:%i:%s') estimate_time,
report_time,connection.status,type,need,
        IF(FLOOR((lapse_time-UNIX_TIMESTAMP())/3600/24)>0,FLOOR((lapse_time-UNIX_TIMESTAMP())/3600/24)+1,0) lapse_time,canal_id,
        staff_id,bind_staff_id,connection.type_data,phone_two_see,phone,phone_two")//strike_data
        ->with(["staff" => function ($query) {
            $query->withField('id,name,mobile,ibec_id');
        }, "canal" => function ($query) {
            $query->withField('id,name');
        }, "bindStaff" => function ($query) {
            $query->withField('id,name,mobile,ibec_id');
        }])->where(["connection.id" => $this->request->param("connection_id")])
            ->find();
        if (empty($list)) $this->error("客户不存在");
        //$scan_num=Scan::where(["connection_id"=>$list["id"]])->count();
        $where = "phone = " . $list["phone"] . " or (phone_two is not null and phone_two=" . $list["phone"] . ") ";
        if (!empty($v["phone_two"])) {
            $where .= " or phone=" . $list["phone_two"] . " or (phone_two is not null and phone_two=" . $list["phone_two"] . ") ";
        }
        $list["scan_num"]=Scan::where("connection_id in (select id from dc_connection where type_data='0' and ".$where." ) and connection_id or connection_id =".$list["id"])
            ->count();
        /*2023-5-27 修改 查看该客户已绑定置业顾问 start*/
        if(empty($list["canal_id"])){
            $canal=\app\common\model\Connection::field("id,name")->where($where)->where(["status"=>'2'])
                ->with(["canal"=>function($query){
                    $query->withField('id,name');
                }])
                ->find();
            if (!empty($canal)){
                $list["canal_id"]=$canal["canal"]["id"];
                $list["canal"]["name"]=$canal["canal"]["name"];
                $list["canal"]["id"]=$canal["canal"]["id"];
            }
        }
        /*2023-5-27 修改 查看该客户已绑定置业顾问 end*/
        $list["staff_ibec_name"]="";
        $list["bindstaff_ibec_name"]="";
        if(!empty($list["staff"]["ibec_id"])){
            $staff_ibec_name=Ibec::field("name")->where(["id"=>$list["staff"]["ibec_id"]])->find();
            $list["staff_ibec_name"]=$staff_ibec_name["name"];
        }
        if(!empty($list["bindStaff"]["ibec_id"])){
            $bindstaff_ibec_name=Ibec::field("name")->where(["id"=>$list["bindStaff"]["ibec_id"]])->find();
            $list["bindstaff_ibec_name"]=$bindstaff_ibec_name["name"];
        }
        $this->success("成功", $list);

    }

    /**
     * 定时任务
     * 处理绑定过期客户
     * */
    public function tasks()
    {
        $model = new \app\common\model\Connection();
        $model->checkExpire();
    }


    /**
     * 定时任务--00执行
     * 昨天报备成功的客户修改为已录入
     * */
    public function reportExpire()
    {
        $model = new \app\common\model\Connection();
        $model->reportExpire();
    }
}
